<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="w-full dialog-form"
      label-width="auto"
      size="small"
      :disabled="dialogType === 'view'"
    >
      <el-form-item label="上级机构" >
        <el-tree-select
          clearable
          :disabled="dialogType === 'add' && originRow.id "
          v-model="ruleForm.parentId"
          placeholder="请选择 上级机构"
          lazy
          node-key="id"
          :filter-node-method="filterNodeMethod"
          filterable
          :load="load"
          check-strictly
          :props="{
            label: 'deptName',
            children: 'children',
            isLeaf: 'isLeaf',
          }"
        >
        </el-tree-select>
      </el-form-item>
      <el-form-item label="部门编号" prop="deptCode" >
        <el-input v-model="ruleForm.deptCode" clearable placeholder="请输入 部门编号"/>
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="ruleForm.deptName" clearable placeholder="请输入 部门名称"/>
      </el-form-item>
      <el-form-item label="部门简称" prop="shortName">
        <el-input v-model="ruleForm.shortName" clearable placeholder="请输入 部门简称"/>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="ruleForm.sort" clearable placeholder="请输入 排序" controls-position="right"/>
      </el-form-item>
      <el-form-item label="部门层级" prop="deptLevel">
        <el-select v-model="ruleForm.deptLevel" clearable placeholder="请选择 部门层级">
          <el-option v-for="item in dept_levelOPTIONS" :label="item.value" :value="item.key"/>
        </el-select>
      </el-form-item>
      <el-form-item label="公司分级" prop="deptCategory">
        <el-select v-model="ruleForm.deptCategory" clearable placeholder="请选择 公司分级">
          <el-option v-for="item in org_categoryOPTIONS" :label="item.value" :value="item.key"/>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts">
  import {defineComponent, getCurrentInstance, reactive, ref, toRaw, nextTick} from "vue";
  import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
  import {getDictDetail} from "@/api/utils";
  import {getOrgList} from "@/api/ERP_sales";

  export default defineComponent({
    name: 'EditForm',
    expose: ['init', 'submitForm',],
    emits: ['init', 'submitForm','register'],
    setup(props, { emit }) {
      const ruleFormRef = ref<FormInstance>()
      const ruleForm = reactive<any>({
        deptName: '',
        shortName: '',
        deptCode: '',
        deptLevel: '',
        deptCategory: '',
        sort: 1,
        parentId: '',
      })
      const rules = reactive<any>({
        parentId:[
          {
            required: true,
            message: '请选择 上级机构',
            trigger: 'change',
          },
        ],
        deptCode: [
          { required: true, message: '请输入 部门编号', trigger: 'blur' },
        ],
        deptName: [
          { required: true, message: '请输入 部门名称', trigger: 'blur' },
        ],
        shortName: [
          { required: true, message: '请输入 部门简称', trigger: 'blur' },
        ],
        sort: [
          { required: true, message: '请输入 排序', trigger: 'blur' },
        ],
        deptLevel: [
          {
            required: true,
            message: '请选择 部门层级',
            trigger: 'change',
          },
        ],
        deptCategory: [
          {
            required: true,
            message: '请选择 公司分级',
            trigger: 'change',
          },
        ],
      })
      const originRow = ref({})
      const dialogType = ref('')
      const submitForm = async () => {
        if (!ruleFormRef.value) return

        const valid = await ruleFormRef.value.validate()

        if (valid) {
          const parentId = Number.isNaN(+ruleForm.parentId) ? originRow.value.id : ruleForm.parentId
          return Promise.resolve({
            form: {
              ...toRaw(ruleForm),
              parentId,
            },
            row: {
              ...toRaw(originRow.value),
            },
            type: dialogType.value
          })
        } else {
          return Promise.reject()
        }
      }


      const resetFields = () => {
        ruleFormRef.value.resetFields()
      }

      const org_categoryOPTIONS = ref([])
      const dept_levelOPTIONS = ref([])
      const initDict = async () => {
        const { data } =  await getDictDetail({
          key: 'org_category'
        })
        org_categoryOPTIONS.value = data.map(v => {
          return {
            ...v,
            key: +v.key,
          }
        })
        const { data: data1 } =  await getDictDetail({
          key: 'dept_level'
        })
        dept_levelOPTIONS.value = data1.map(v => {
          return {
            ...v,
            key: +v.key,
          }
        })
      }

      const init = async (type, row) => {
        originRow.value = row
        await initDict()
        dialogType.value= type
        if(type === 'add') {
          const newFormData = {
            parentId: '',
          }
          if(row.id) {
            newFormData.parentId = row.parentName
          }

          Object.assign(ruleForm, newFormData);
        }else if(row.id) {
          const newFormData = {
            deptName: row.deptName,
            shortName: row.shortName,
            deptCode: row.deptCode,
            deptLevel: row.deptLevel,
            deptCategory: row.deptCategory,
            sort: row.sort,
            parentId: row.parentName,
          };
          Object.assign(ruleForm, newFormData);
        }
      }

      const instance = getCurrentInstance()
      emit('register', instance)

      const filterNodeMethod = (value, data) => {
        return data.deptName.includes(value)
      }
      const load = async (node, resolve) => {
        if (node.isLeaf) return resolve([])
        const { data } = await getOrgList({
          parentId: node.data.id,
        })
        const data1 = data.map(v => {
          return {
            ...v,
            value: v.id,
            isLeaf: !v.hasChildren,
          }
        })
        resolve(data1)
      }


      return {
        init,
        submitForm,
        resetFields,
        rules,
        ruleForm,
        ruleFormRef,
        org_categoryOPTIONS,
        dept_levelOPTIONS,
        dialogType,
        originRow,
        filterNodeMethod,
        load,
      }
    }
  })
</script>
<style lang="scss">
  .dialog-form {
    .el-input-number {
      width: 100%!important;
      input {
        text-align: left;
      }
    }
  }
</style>
